package core

import (
	"fmt"
	_ "github.com/coreos/bbolt"
	"github.com/kataras/golog"
	"github.com/kataras/iris"
	"github.com/kataras/iris/middleware/recover"
)

var app *iris.Application
var banner string

func init() {
	app = iris.New()
	//初始化恢复机制
	app.Use(recover.New())
	//initLogs(app.Logger())
	//日志处理机制
	//TODO 文件日志实现
	app.Logger().SetLevel("debug")
	//加载文件配置
	loadConfig()
	initDatabase()
	InitSession()
	//初始化缓存实现
	// close and unlock the database when control+C/cmd+C pressed
	iris.RegisterOnInterrupt(func() {
		Close()
	})
	banner = `====================================================================================================================

                    欢迎使用 %s - Powered By 林芳崽

====================================================================================================================`
	app.Logger().Info("程序启动中...\r\n" + fmt.Sprintf(banner, GetAppName()))

	//初始化websocket
	setupWebsocket(app)

}

func Close()  {
	if(sessionDb!=nil) {
		sessionDb.Close()
	}
	closeDatabase()
	closeWebSocket();
}

func Run() {
	app.Run(iris.Addr(ListenAddr()), iris.WithoutServerError(iris.ErrServerClosed))
}

func GetApp() *iris.Application {
	return app
}

func Logger() *golog.Logger {
	return app.Logger()
}

func Banner() string {
	return fmt.Sprintf(banner, GetAppName())
}
